package com.whfc.emp.service.impl;

import com.whfc.common.enums.FenceType;
import com.whfc.common.enums.LocaleState;
import com.whfc.common.exception.BizException;
import com.whfc.common.geometry.GeometryUtil;
import com.whfc.common.geometry.Point;
import com.whfc.common.geometry.Polygon;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.PositionUtil;
import com.whfc.emp.dao.*;
import com.whfc.emp.dto.*;
import com.whfc.emp.entity.AppEmp;
import com.whfc.emp.enums.AttendState;
import com.whfc.emp.manager.AppEmpDataManager;
import com.whfc.emp.manager.CommonEmpConfigManager;
import com.whfc.emp.service.AppEmpIndexService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClasssName AppEmpIndexServiceImpl
 * @Description 首页相关的接口服务
 * @Author hw
 * @Date 2020/12/30 11:29
 * @Version 1.0
 */
@DubboService(interfaceClass = AppEmpIndexService.class, version = "1.0.0", timeout = 5000)
public class AppEmpIndexServiceImpl implements AppEmpIndexService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppEmpMapper appEmpMapper;

    @Autowired
    private AppEmpDataManager appEmpDataManager;

    @Autowired
    private AppEmpEnterRecordMapper appEmpEnterRecordMapper;

    @Autowired
    private AppEmpDayMapper appEmpDayMapper;

    @Autowired
    private CommonEmpConfigManager commonEmpConfigManager;

    @Autowired
    private AppFenceMapper appFenceMapper;

    @Autowired
    private AppEmpGroupMapper appEmpGroupMapper;


    @Override
    public List<AppWorkTypeDTO> getWorkTypeList(Integer deptId) {
        logger.info(" 获取可供选择的工种或者岗位,deptId：{}", deptId);
        return appEmpMapper.selectWorkTypeList(deptId);
    }

    @Override
    @Deprecated
    public IndexEmpListDTO getEmpList(Integer deptId, String keyword, Integer attendState, Integer empId, Integer localeState, Integer groupId) {
        logger.info("获取首页人员列表,deptId：{},keyword：{},attendState：{},empId：{},localeState：{},groupId：{}", deptId, keyword, attendState, empId, localeState, groupId);
        List<AppEmpDTO> empList = appEmpMapper.selectIndexEmpList(deptId, keyword, attendState, localeState, groupId, empId);
        Integer total = empList.size();
        Integer attendNum = 0;
        Integer localeNum = 0;
        for (AppEmpDTO appEmpDTO : empList) {
            Integer localeState1 = appEmpDTO.getLocaleState();
            Integer attendState1 = appEmpDTO.getAttendState();

            if (AttendState.ATTEND.getValue().equals(attendState1)) {
                attendNum++;
                if (LocaleState.IN.getValue().equals(localeState1)) {
                    localeNum++;
                }
            }
            //人员图标处理
            HelmetIconDTO helmetIcon = appEmpDataManager.getHelmetIcon(appEmpDTO.getColor());
            BeanUtils.copyProperties(helmetIcon, appEmpDTO);
        }
        IndexEmpListDTO data = new IndexEmpListDTO();
        data.setEmpList(empList);
        data.setTotal(total);
        data.setAbsentNum(total - attendNum);
        data.setOutLocaleNum(attendNum - localeNum);
        data.setLocaleNum(localeNum);
        data.setAttendNum(attendNum);
        return data;
    }

    @Override
    public AppEmpDetailDTO getEmpDetail(Integer empId) {
        logger.info("首页获取人员详细信息,empId:{}", empId);
        AppEmp appEmp = appEmpMapper.selectByPrimaryKey(empId);
        if (appEmp == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该人员不存在");
        }
        AppEmpDetailDTO appEmpDetailDTO = new AppEmpDetailDTO();
        BeanUtils.copyProperties(appEmp, appEmpDetailDTO);
        appEmpDetailDTO.setEmpId(empId);
        //查看最近打卡时间
        Date recentEnterTime = appEmpEnterRecordMapper.selectRecentEnterTime(empId);
        appEmpDetailDTO.setRecentEnterTime(recentEnterTime);
        //查看今天的出勤时长
        Date startTime = DateUtil.getDateBegin(new Date());
        Date endTime = DateUtil.getDateEnd(new Date());
        List<AppEmpDayWorkTimesDTO> appEmpDayWorkTimesDTOS = appEmpDayMapper.selectWorkTimesByEmpId(empId, startTime, endTime);
        if (appEmpDayWorkTimesDTOS != null && appEmpDayWorkTimesDTOS.size() > 0) {
            appEmpDetailDTO.setAttendTimes(appEmpDayWorkTimesDTOS.get(0).getWorkTimes());
        } else {
            appEmpDetailDTO.setAttendTimes(0D);
        }
        return appEmpDetailDTO;
    }

    @Override
    public List<AppEmpDTO> getMapEmpList(Integer deptId, Integer groupId, String empName) {
        logger.info("获取地图人员列表,deptId{}", deptId);
        List<AppEmpDTO> empList = appEmpMapper.selectIndexEmpList(deptId, empName, null, null, groupId, null);
        // 安全帽离线或关机时长
        AppEmpSettingDTO data = commonEmpConfigManager.getMinutes(deptId);
        Date time = DateUtil.addMinutes(new Date(), -data.getMinutes());
        String polygonWKT = commonEmpConfigManager.getPolygonWKT(deptId);
        empList = empList.stream().filter(appEmpDTO -> {
            // 筛选出地图显示的人员
            Date time1 = appEmpDTO.getTime();
            Double lat = appEmpDTO.getLat();
            Double lng = appEmpDTO.getLng();
            if (!PositionUtil.contains(FenceType.POLYGON.value(), polygonWKT, null, lat, lng) || time1 == null || time1.before(time)) {
                return false;
            }
            // 人员图标处理
//            HelmetIconDTO helmetIcon = appEmpDataManager.getHelmetIcon(appEmpDTO.getColor());
            String avatar = appEmpDTO.getAvatar();
            appEmpDTO.setIconUrl(avatar);
            return true;
        }).collect(Collectors.toList());
        return empList;
    }

    @Override
    public List<MapEmpPolyDTO> getMapEmpPoly(Integer deptId, Integer groupId, String empName, Integer fenceId) throws BizException {
        logger.info("获取地图页人员聚合,deptId:{},groupId:{},empName:{},fenceId:{}", deptId, groupId, empName, fenceId);
        List<MapEmpPolyDTO> result = new ArrayList<>();
        // 查找电子围栏
        List<AppFenceDTO> list = appFenceMapper.selectByFenceId(deptId, fenceId);
        if (list.size() == 0) {
            return Collections.emptyList();
        }
        // 获取要显示的人员
        List<AppEmpDTO> mapEmpList = this.getMapEmpList(deptId, groupId, empName);

        for (AppFenceDTO appFenceDTO : list) {
            Integer type = appFenceDTO.getType();
            this.translate(appFenceDTO);
            String polygon = appFenceDTO.getPolygon();
            String center = appFenceDTO.getCenter();
            Double radius = appFenceDTO.getRadius();
            String geomWtk = FenceType.CIRCLE.value().equals(type) ? center : polygon;

            List<AppEmpDTO> empList = new ArrayList<>();
            for (AppEmpDTO appEmpDTO : mapEmpList) {
                // 筛选出该电子围栏的人员
                Double lat = appEmpDTO.getLat();
                Double lng = appEmpDTO.getLng();
                if (PositionUtil.contains(type, geomWtk, radius, lat, lng)) {
                    empList.add(appEmpDTO);
                }
            }

            MapEmpPolyDTO data = new MapEmpPolyDTO();
            BeanUtils.copyProperties(appFenceDTO, data);
            data.setEmpList(empList);
            data.setEmpNum(empList.size());
            result.add(data);
        }
        return result;
    }


    @Override
    public List<MapEmpGroupDTO> getMapEmpFvs(Integer deptId, Integer groupId, String empName, Integer fvsDeviceId) throws BizException {
        logger.info("地图人员列表（班组视频监控),deptId:{},groupId:{},empName:{},fvsDeviceId:{}", deptId, groupId, empName, fvsDeviceId);
        //查找有视频监控的班组
        List<MapEmpGroupDTO> list = appEmpGroupMapper.selectFvsGroup(deptId, groupId, fvsDeviceId);
        if (list.isEmpty()) {
            return Collections.emptyList();
        }

        // 安全帽离线或关机时长
        AppEmpSettingDTO data = commonEmpConfigManager.getMinutes(deptId);
        Date time = DateUtil.addMinutes(new Date(), -data.getMinutes());
        String polygonWkt = commonEmpConfigManager.getPolygonWKT(deptId);

        for (MapEmpGroupDTO mapEmpGroupDTO : list) {
            Integer empGroupId = mapEmpGroupDTO.getGroupId();
            //查找每个班组下面的人员
            List<AppEmpDTO> empList = appEmpMapper.selectIndexEmpList(deptId, empName, null, null, empGroupId, null);
            List<AppEmpDTO> groupEmpList = new ArrayList<>();
            for (AppEmpDTO appEmpDTO : empList) {
                // 筛选出地图显示的人员
                Date time1 = appEmpDTO.getTime();
                Double lat = appEmpDTO.getLat();
                Double lng = appEmpDTO.getLng();
                if (!PositionUtil.contains(FenceType.POLYGON.value(), polygonWkt, null, lat, lng) || time1 == null || time1.before(time)) {
                    continue;
                }
                // 人员图标处理
                HelmetIconDTO helmetIcon = appEmpDataManager.getHelmetIcon(appEmpDTO.getColor());
                appEmpDTO.setIconUrl(helmetIcon.getIconUrl());
                groupEmpList.add(appEmpDTO);
            }
            mapEmpGroupDTO.setEmpNum(groupEmpList.size());
            mapEmpGroupDTO.setEmpList(groupEmpList);
        }
        return list;
    }

    /**
     * 转换空间几何对象
     *
     * @param appFenceDTO 电子围栏对象
     */
    private void translate(AppFenceDTO appFenceDTO) {
        if (FenceType.POLYGON.value().equals(appFenceDTO.getType())) {
            Polygon polygon = GeometryUtil.decodePolygon(appFenceDTO.getPolygon());
            appFenceDTO.setPolygonPointList(polygon.getPointList());
            appFenceDTO.setPolygon(null);
        }
        //圆形
        String center = appFenceDTO.getCenter();
        if (StringUtils.isNotBlank(center)) {
            Point point = GeometryUtil.decodePoint(center);
            appFenceDTO.setCenterPoint(point);
            appFenceDTO.setCenter(null);
        }
    }
}
